import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { TranslatorService } from '../services/translator.service';

interface Translation {
  id: string;
  sourceText: string;
  translatedText: string;
  timestamp: number;
  sourceLanguage: string;
  targetLanguage: string;
}

interface TranslatorState {
  translations: Translation[];
  isLoading: boolean;
  error: string | null;
  translate: (text: string, from: string, to: string, autoPlay?: boolean) => Promise<void>;
  clearTranslations: () => void;
}

export const useTranslatorStore = create<TranslatorState>()(
  persist(
    (set, get) => ({
      translations: [],
      isLoading: false,
      error: null,

      translate: async (text: string, from: string, to: string, autoPlay = false) => {
        if (!text.trim()) return;

        set({ isLoading: true, error: null });

        try {
          const { translation, detected_language } = await TranslatorService.translate(
            text,
            from,
            to
          );
          
          const newTranslation = {
            id: Date.now().toString(),
            sourceText: text,
            translatedText: translation,
            timestamp: Date.now(),
            sourceLanguage: from === 'auto' ? detected_language : from,
            targetLanguage: to,
          };

          set(state => ({
            translations: [...state.translations, newTranslation],
            isLoading: false,
          }));

          if (autoPlay) {
            await TranslatorService.textToSpeech(translation, to);
          }
        } catch (error) {
          console.error('Translation error:', error);
          set({ 
            error: '翻译失败，请稍后重试',
            isLoading: false,
          });
        }
      },

      clearTranslations: () => set({ translations: [] }),
    }),
    {
      name: 'translator-storage',
      partialize: (state) => ({
        translations: state.translations,
      }),
    }
  )
);